package com.osdp.gateway.util;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.common.collect.Maps;
import com.osdp.gateway.entity.JWTInfo;

import java.util.Date;
import java.util.Map;

public class JwtUtil {
    /**
     * 解析token，得到userId,userName,superAdmin,nowTenanl
     * @param token
     * @return info JWTInfo
     */
    public static JWTInfo getInfo(String token){
        DecodedJWT jwt = JWT.decode(token);
        String s = jwt.getClaim("info").asString();//Get the info from token claim(要求，声言).
        JSONObject o  = JSONObject.parseObject(s);
        JWTInfo info = new JWTInfo(o.getString("userId"),o.getString("userName"),
                o.getBoolean("superAdmin"), o.getString("nowTenant"));
        return info;
    }

    public static String getTenantId(String token){
        try {
            return getInfo(token).getNowTenant();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static String getUserId(String token){
        try{
            return getInfo(token).getUserId();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static String getUsername(String token){
        try{
            return getInfo(token).getUserName();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
    //-----------------------测试------------------------------------
    private static  final  long EXPIRE_DATE = 30*60*100000;//设置过期时间
    private static  final  String TOKEN_SECRET = "ZCEQIUBFKSJBFJH2020BQWE";//token秘钥
    public static String generateToken(JWTInfo info){
        String token = "";
        StringBuffer s = new StringBuffer();
        s.append("{'userId':'").append(info.getUserId())
                .append("','userName':'").append(info.getUserName())
                .append("','superAdmin':'").append(info.isSuperAdmin())
                .append("','nowTenant':'").append(info.getNowTenant()).append("'}");
        try{
            //过期时间
            Date date = new Date(System.currentTimeMillis()+ EXPIRE_DATE);
            //秘钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String,Object> header = Maps.newHashMap();
            header.put("typ","JWT");
            header.put("alg","HS256");
            //携带username，password信息，生成签名
            token = JWT.create()
                    .withHeader(header)
                    .withClaim("info",s.toString())
                    //.withClaim("password",password).withExpiresAt(date)
                    .sign(algorithm);
        }catch (Exception e){
            e.printStackTrace();
        }
        return token;
    }
    public static boolean verify(String token){
        /**
         * @desc   验证token，通过返回true
         * @params [token]需要校验的串
         **/
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return  false;
        }
    }
}
